package com.bwie.service.Impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.Main;
import com.bwie.pojo.Menu;
import com.bwie.pojo.Role;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginFromVo;
import com.bwie.vo.RegFromVo;
import com.mysql.jdbc.log.Log;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.mapper.UserMapper;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Override
    public R sendPhoneCode(String userMobile) {
        String PhoneCode = RandomUtil.randomNumbers(4);
        String phoneCodeKey = "phoneCode-"+userMobile;
        redisTemplate.opsForValue().set(phoneCodeKey,PhoneCode,5, TimeUnit.MINUTES);
        MobileMessageUtil.sendMobileMessage(userMobile,PhoneCode);
        return R.OK();
    }

    @Override
    public R login(LoginFromVo loginFromVo) {
        User user = userMapper.selectOne(
                new QueryWrapper<User>().lambda().eq(User::getUserMobile, loginFromVo.getUserMobile())
        );
        if(ObjectUtils.isEmpty(user)){
            return R.ERROR(500,"手机号未注册");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if(!bCryptPasswordEncoder.matches(loginFromVo.getUserPass(),user.getUserPass())){
            return R.ERROR(500,"密码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getUserId())
                .claim("userName",user.getUserName())
                .compact();
        String tokenKey = "token-"+user.getUserId();
        List<String> users = userMapper.selectRoleName(user.getUserId());
        user.setToken(token);
        user.setUserList(users);
        redisTemplate.opsForValue().set(tokenKey,token,20,TimeUnit.MINUTES);
        return R.OK(user);
    }

    @Override
    public R getReg(RegFromVo regFromVo) {
        User user = userMapper.selectOne(
                new QueryWrapper<User>().lambda().eq(User::getUserMobile, regFromVo.getUserMobile())
        );
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(regFromVo.getUserPass());
        System.out.println("明文密码:"+regFromVo.getUserPass());
        System.out.println("加密密码:"+encode);
        if(ObjectUtils.isNotEmpty(user)){
            if(!user.getUserPass().equalsIgnoreCase(encode)){
                return R.ERROR(500,"密码错误");
            }
            String phoneCodeKey = "phoneCode-"+user.getUserMobile();
            String redisPhoneCode = redisTemplate.opsForValue().get(phoneCodeKey);
            if(StringUtils.isEmpty(redisPhoneCode)){
                return R.ERROR(500,"手机号验证码不存在");
            }
            if(!redisPhoneCode.equalsIgnoreCase(regFromVo.getPhoneCode())){
                return R.ERROR(500,"手机号验证码错误");
            }
        }else {
            User user1 = new User();
            user1.setUserName("管理员");
            user1.setUserMobile(regFromVo.getUserMobile());
            user1.setUserPass(encode);
            user1.setCreateBy("用户");
            user1.setUpdateTime(new Date());
            userMapper.insert(user1);
        }
        return R.OK();
    }

    @Override
    public R getTreeList() {
        String token = request.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer id = body.get("userId", Integer.class);
        List<Menu> menuList = userMapper.selectTreeList(id);
        List<Tree<Integer>> path = TreeUtil.build(menuList, 0, (tree, treeNode) -> {
            treeNode.setId(tree.getMenuId());
            treeNode.setName(tree.getMenuName());
            treeNode.setParentId(tree.getMenuPid());
            treeNode.putExtra("path", tree.getMenuPath());
        });
        return R.OK(path);
    }
}